package com.example.demo.controller;


import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.common.constant.Const;
import com.example.demo.common.lang.Result;
import com.example.demo.pojo.SysUser;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author example
 * @since 2022-09-23
 */
@RestController
@RequestMapping("/sys/user")
public class SysUserController extends BaseController{

    @GetMapping("/list")
    public Result list( String username){

            Page<SysUser> pageData = sysUserService.page(getPage(), new QueryWrapper<SysUser>()
                    .like(StrUtil.isNotBlank(username), "username", username));

            return Result.succ(pageData);
    }


    @GetMapping("/info/{id}")
    public Result info(@PathVariable(name = "id") Long id) {
        return Result.succ(sysUserService.getById(id));
    }

    @PostMapping("/save")
    public Result save(@Validated @RequestBody SysUser sysUser){
        sysUser.setCreated(LocalDateTime.now());
        // 初始默认密码
//        sysUser.setPassword(Const.DEFULT_PASSWORD.getCode());
        if (StrUtil.isBlank(sysUser.getPassword())) {
            return Result.fail("密码不能为空");
        }
        sysUserService.save(sysUser);
        return Result.succ(sysUser);

    }

    @PostMapping("/update")
    public Result update(@Validated @RequestBody SysUser sysUser){

        sysUser.setUpdated(LocalDateTime.now());

        sysUserService.updateById(sysUser);

        return Result.succ(sysUser);
    }

    @Transactional
    @PostMapping("/delete")
    public Result delete(@RequestBody Long[] ids){

        sysUserService.removeByIds(Arrays.asList(ids));

        return Result.succ("删除成功");
    }

}

